// pages/accountInfo/accountInfo.js
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    accountList: [],
    source: ''
  },
  toDetail(e) {
    let account = e.currentTarget.dataset.account ? JSON.stringify(e.currentTarget.dataset.account) : '';
    let hasDefault = 0,
      {
        accountList
      } = this.data;
    if (accountList && accountList.length <= 0) {
      hasDefault = 1
    }
    wx.navigateTo({
      url: '/pages/accountEdit/accountEdit?account=' + account + '&hasDefault=' + hasDefault,
    })
  },
  delete(e) {
    let {
      account
    } = e.currentTarget.dataset;
    let that = this;
    Dialog.confirm({
      title: '确认删除',
      message: '确定删除该账户信息？',
      asyncClose: true,
      className: 'btnWidth'
    }).then(() => {
      wx.$api.deleteAccount({
        natural_account_id: account.natural_account_id
      }).then(res => {
        Dialog.close();
        if (parseInt(res.data.code) != 200) {
          return wx.$Toast(res.data.msg);
        }
        that.getAccountData();
      })
    }).catch(() => {
      Dialog.close();
    });
  },
  toPrevPage(e) {
    if (this.data.source === "index") {
      return;
    }
    let pages = getCurrentPages();

    let that = pages[pages.length - 2];
    let delta = 1;
    if (that.changeAccountInfo == undefined) {
      that = pages[pages.length - 4];
      delta = 3;
    }
    if (that.changeAccountInfo && typeof that.changeAccountInfo == 'function') {
      that.changeAccountInfo({
        account: e.currentTarget.dataset.account
      });
      wx.navigateBack({
        delta: delta,
        complete: (res) => {},
      })
    }
  },

  getAccountData() {
    wx.showLoading({
      title: '加载中...',
    })
    wx.$api.getAccountData().then(res => {
      wx.hideLoading();
      if (res.data.code == 200) {
        this.setData({
          accountList: res.data.data.lists
        })
      }
    }).catch(ret => {
      wx.$Toast(ret.msg || "服务繁忙")
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      source: options.source
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getAccountData();
    let pages = getCurrentPages();
    let that = pages[pages.length - 2];
    that.setData({
      isLoadAccount:false
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})